<?php

namespace App\Console\Commands;

use App\Models\Collection\RepaySummary;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecord;
use App\Facades\MoneyPlatformRequestFacade;
use Log;
class RepairRepayCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'repair:repay {action : test|ocrs|updateLendMoney} {--time=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'repair repay data';

    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['test', 'ocrs','updateLendMoney'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'test', 'ocrs'.");
            exit(1);
        }
    }

    protected function runAction()
    {
        $this->{$this->action}();
    }

    //todo 还款用身份证修复查询用
    public function ocrs()
    {
        //获取各用户目前最新的身份证
//        DB::connection('backend')
//            ->table('user_cert_ocrs')
//            ->
        $test = DB::connection('backend')
            ->table('repay_summaries')
            ->select(['uid'])
            ->where('status', RepaySummary::STATUS_ONE)
            ->whereNotExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('repair_user_cert_ocrs')
                    ->whereRaw('repay_summaries.uid = repair_user_cert_ocrs.user_id');
            })
            ->orderBy('repay_summaries.id', 'asc')
            ->toSql();
        print_r($test);exit;
//            ->chunk(10, function ($summaries) {
//
//
//                print_r($summaries);exit;
//            });
        $test = DB::connection('backend')
            ->table('user_cert_ocrs')
//            ->where('')
            ->get();
        var_dump($test);exit;
        $this->info('repair_ocrs_done');
    }

    public function test()
    {
        $this->info('test');
    }

    public function updateLendMoney(){
        $time = $this->option('time');
        $timearray = explode(':',$time);
        $todat = Carbon::now()->toDateString();
        $startTime =  isset($timearray[0])?$timearray[0]:$todat;
        $endTime   = isset($timearray[1])? $timearray[1]:$todat;
        $moneyInfo = RepayRecordMoney::where('repay_record_moneys.status',RepayRecordMoney::STATUS_FOUR)
                    ->whereBetween('repay_date',[$startTime,$endTime])
                    ->leftJoin('repay_summaries as a', 'repay_record_moneys.summary_id', '=', 'a.id')
                    ->select(['repay_record_moneys.*','a.loan_id'])
                    ->get();
        foreach($moneyInfo as $value){
            $record = RepayRecord::find($value->record_id);
            $data1['loanId'] = $value->loan_id;
            $data1['period'] = $value->period;
            $result = MoneyPlatformRequestFacade::getRepayPlan($data1);
            $data = isset($result['data']) ? $result['data'] : '';
            if(!empty($data)) {
                if(empty($data['status'])){
                    continue;
                }
                $is_success = RepayRecordMoney::getMoneyPlanStatus($data['status']);
                if($is_success) {
                    if($record->money->lending_money == $data['interestAmount']){
                        continue;
                    }
                    Log::debug('repair_money_lending', ['message'=>['原始数据的利息'.$record->money->lending_money.'----重亲请求的利息'.$data['interestAmount'],'data'=>$data1]]);
                    $record->money->lending_money = $data['interestAmount'];
                    $record->money->save();
                }
            }
        }
        $this->info('执行完成');

    }
}
